package com.beiing.tianshuai.tianshuai.mine.ui;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.adapter.OrderAfterSaleStateAdapter;
import com.beiing.tianshuai.tianshuai.app.AppConstant;
import com.beiing.tianshuai.tianshuai.app.HttpRequestConstant;
import com.beiing.tianshuai.tianshuai.base.BaseActivity;
import com.beiing.tianshuai.tianshuai.event.EventConstant;
import com.beiing.tianshuai.tianshuai.event.messages.OrderListEvent;
import com.beiing.tianshuai.tianshuai.mine.entity.OrderRefundCancelBean;
import com.beiing.tianshuai.tianshuai.mine.entity.OrderRefundStateDataBean;
import com.beiing.tianshuai.tianshuai.mine.presenter.OrderAfterSaleStatePresenter;
import com.beiing.tianshuai.tianshuai.mine.view.OrderAfterSaleStateViewImpl;
import com.beiing.tianshuai.tianshuai.rx.RxBus;
import com.beiing.tianshuai.tianshuai.util.DensityUtils;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.widget.CustomDialog;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;

import java.text.MessageFormat;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 退款流程页面
 *
 * @author 赵皓
 */
public class OrderAfterSaleStateActivity extends BaseActivity implements OrderAfterSaleStateViewImpl {

    /**
     * toolbar返回按钮
     */
    @BindView(R.id.toolbar_navigation_back)
    ImageButton toolbarNavigationBack;

    /**
     * toolbar 更多按钮
     */
    @BindView(R.id.toolbar_filter_more)
    ImageButton toolbarFilterMore;

    /**
     * 货物照片
     */
    @BindView(R.id.iv_ex_tickets)
    ImageView ivExTickets;

    /**
     * 货物照片上的货物数量
     */
    @BindView(R.id.tv_goods_number)
    TextView tvGoodsNumber;

    /**
     * 退货原因
     */
    @BindView(R.id.tv_after_sale_because)
    TextView tvAfterSaleBecause;

    /**
     * 退款金额
     */
    @BindView(R.id.tv_after_sale_money)
    TextView tvAfterSaleMoney;

    /**
     * 退回账户
     */
    @BindView(R.id.tv_after_sale_money_back_mode)
    TextView tvAfterSaleMoneyBackMode;

    /**
     * 退款信息列表
     */
    @BindView(R.id.rv_after_sale_info)
    RecyclerView rvAfterSaleInfo;

    /**
     * 返回首页按钮
     */
    @BindView(R.id.tv_back)
    TextView tvBack;

    /**
     * 联系卖家按钮
     */
    @BindView(R.id.tv_contact_seller)
    TextView tvContactSeller;

    /**
     * toolbar标题
     */
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;

    /**
     * 底部装填按钮布局
     */
    @BindView(R.id.rl_bottom_view)
    RelativeLayout rlBottomView;

    private static final String TAG = "OrderAfterSaleStateActi";

    /**
     * 订单id
     */
    private String mOrderId;

    /**
     * 退货状态主持人
     */
    private OrderAfterSaleStatePresenter mPresenter;

    private OrderAfterSaleStateAdapter mAdapter;

    /**
     * 接收订单id
     *
     * @param activity 上一个activity
     * @param orderId  订单id
     */
    public static void startActivityForResult(Activity activity, String orderId) {
        Intent intent = new Intent(activity, OrderAfterSaleStateActivity.class);
        intent.putExtra("orderId", orderId);
        //强转返回参数,请求码,取消售后！！！
        activity.startActivityForResult(intent, AppConstant.REQUEST_CODE_CANCEL_REFUND);
    }

    /**
     * 接收订单id
     *
     * @param activity 上一个activity
     * @param orderId  订单id
     */
    public static void start(Activity activity, String orderId) {
        Intent intent = new Intent(activity, OrderAfterSaleStateActivity.class);
        intent.putExtra("orderId", orderId);
        //强转返回参数,请求码,取消售后！！！
        activity.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_order_after_sale_state;
    }

    @Override
    protected void init() {
        initIntentExtras();
        initRecyclerView();
        initPresenter();
        initListener();
    }

    /**
     * 进入就请求退货状态数据
     */
    private void initPresenter() {
        mPresenter = new OrderAfterSaleStatePresenter(this);
        //mOrderId
        mPresenter.getOrderAfterSaleState(mOrderId);
    }

    private void initListener() {
        toolbarNavigationBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        toolbarFilterMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showShortText("更多信息，敬请期待");
            }
        });
        tvContactSeller.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showShortText("联系卖家");
            }
        });
        mAdapter.setOnClickListener(new OrderAfterSaleStateAdapter.OnItemClickListener() {
            @Override
            public void onHelpClickListener() {
                showShortText("帮助？不存在的");
            }
        });
    }

    /**
     * 初始化RecyclerView
     */
    private void initRecyclerView() {
        //创建LinearLayoutManager 对象
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        //设置RecyclerView 布局
        rvAfterSaleInfo.setLayoutManager(mLayoutManager);
        //不需要分割线
        rvAfterSaleInfo.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                outRect.set(10, 10, 10, 10);
            }
        });
        //设置Adapter
        mAdapter = new OrderAfterSaleStateAdapter(mContext);
        rvAfterSaleInfo.setAdapter(mAdapter);
    }

    /**
     * 获取id
     */
    private void initIntentExtras() {
        Intent intent = getIntent();
        mOrderId = intent.getStringExtra("orderId");
    }

    @Override
    public void getOrderAfterSaleStateSuccess(OrderRefundStateDataBean bean) {
        int code = bean.getCode();
        switch (code) {
            case 200:
                //退货类型
                toolbarTitle.setText(bean.getData().getRefundType());
                tvAfterSaleBecause.setText(MessageFormat.format("退款原因：{0}", bean.getData().getReason()));
                tvAfterSaleMoney.setText(MessageFormat.format("退款金额：{0}元", bean.getData().getAmountMoney()));
                tvAfterSaleMoneyBackMode.setText(MessageFormat.format("退回账户：{0}", bean.getData().getPayMethod()));
                tvGoodsNumber.setText(MessageFormat.format("共{0}件商品", bean.getData().getCount()));

                //非票务类照片比例参数
                RequestOptions goodsPhotoOptions = new RequestOptions()
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .centerCrop()
                        .placeholder(R.drawable.default_avatar)
                        .override(90, 90);
                //非票务类图片
                Glide.with(mContext.getApplicationContext())
                        .load(HttpRequestConstant.ACTIVITY_PIC_HEAD + bean.getData().getImgurl())
                        .apply(goodsPhotoOptions)
                        .into(ivExTickets);

                //动态改变按钮    暂时显示状态 字段为is_status
//                0为等待商家确认   取消退款      联系卖家
//                1为商家同意退款   返回首页      联系卖家
//                2为商家拒绝退款   重新申请      联系卖家
//                3为退款成功       返回首页      联系卖家
//                4为退款失败       返回首页      联系卖家
                Drawable drawable = ContextCompat.getDrawable(mContext, R.drawable.shape_bg_btn_radio_100_gray);
                //返回首页按钮
                TextView tvBackOrderData = getBake(drawable);
                LogUtils.i("id" + bean.getData().getId(), TAG);
                if (TextUtils.equals(bean.getData().getIsStatus(), null)) {
                    showShortText("不存在状态，数据空");
                    break;
                }
                //为空
                switch (bean.getData().getIsStatus()) {
                    case "0":
                        //tvBack.setText("取消退款");
                        //取消退款
                        TextView tvRefund = getRefund(drawable, bean);
                        rlBottomView.addView(tvRefund);
                        break;
                    case "1":
                        //tvBack.setText("返回首页");
                        rlBottomView.addView(tvBackOrderData);
                        break;
                    case "2":
                        // tvBack.setText("重新申请");
                        TextView tvAgainRequest = getAgainRequest(drawable, bean);
                        rlBottomView.addView(tvAgainRequest);
                        break;
                    case "3":
                        //tvBack.setText("返回首页");
                        rlBottomView.addView(tvBackOrderData);
                        break;
                    case "4":
                        //tvBack.setText("返回首页");
                        rlBottomView.addView(tvBackOrderData);
                        break;
                    default:
                        break;
                }
                //加载数据
                List<OrderRefundStateDataBean.DataBean.ProcessBean> processBeans = bean.getData().getProcess();
                //插入第一条本地数据
                OrderRefundStateDataBean.DataBean.ProcessBean processBean = new OrderRefundStateDataBean.DataBean.ProcessBean();
                processBean.setTree(true);
                processBean.setStatus("等待卖家确认");
                processBean.setStatusdef("退款申请已受理，请等待卖家确认");
                processBean.setTime(bean.getData().getCtime());
                processBeans.add(0, processBean);
                mAdapter.updateData(processBeans);
                break;
            case 401:
                showShortText("参数错误");
                break;
            case 202:
                showShortText("请求失败");
                break;
            default:
                break;
        }
    }

    /**
     * 创建退出售后按钮
     *
     * @param drawable shape背景
     * @param bean     数据要传递订单号
     * @return 取消售后按钮
     */
    private TextView getRefund(Drawable drawable, final OrderRefundStateDataBean bean) {
        View.OnClickListener onClickListenerDeleteOrder = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //showShortText("取消退款");
                //bean.getData().getIsStatus();
                CustomDialog dialog = new CustomDialog(mContext, R.style.dialog, "确认取消售后吗？", new CustomDialog.OnCloseListener() {
                    @Override
                    public void onClick(Dialog dialog, boolean confirm) {
                        if (confirm) {
                            mPresenter.getOrderCancelRefundCode(mOrderId);
                            dialog.dismiss();
                        } else {
                            dialog.dismiss();
                        }
                    }
                }).setNegativeButton("取消").setPositiveButton("确认").setTitle("提示");
                dialog.setCanceledOnTouchOutside(true);
                dialog.show();

            }
        };
        return createTextView("取消售后", onClickListenerDeleteOrder, drawable);
    }

    /**
     * 重新请求按钮
     *
     * @param drawable shape背景
     * @param bean     数据要传递订单号
     * @return 重新请求按钮
     */
    private TextView getAgainRequest(Drawable drawable, final OrderRefundStateDataBean bean) {
        View.OnClickListener onClickListenerDeleteOrder = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showShortText("重新请求");
                OrderApplyAfterSaleActivity.start(mContext, mOrderId);
                finish();
            }
        };
        return createTextView("重新请求", onClickListenerDeleteOrder, drawable);
    }

    /**
     * 返回首页按钮
     *
     * @param drawable shape背景
     * @return 按钮
     */
    private TextView getBake(Drawable drawable) {
        View.OnClickListener onClickListenerDeleteOrder = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        };
        return createTextView("返回首页", onClickListenerDeleteOrder, drawable);
    }

    /**
     * 封装动态创建按钮方法
     *
     * @param text            按钮文字
     * @param onClickListener 按钮点击事件
     * @param drawable        按钮背景
     * @return 返回text view
     */
    private TextView createTextView(String text, View.OnClickListener onClickListener, Drawable drawable) {
        TextView textView = new TextView(mContext);
        textView.setText(text);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
        //textView.setRight(10);      不可以直接这样写
        textView.setTextColor(ContextCompat.getColor(mContext, R.color.black));
        textView.setGravity(Gravity.CENTER);
        textView.setBackground(drawable);
        textView.setOnClickListener(onClickListener);
        LinearLayout.LayoutParams olp = new LinearLayout.LayoutParams(DensityUtils.dp2px(mContext, 84), DensityUtils.dp2px(mContext, 32));
        olp.setMargins(0, 0, 0, 0);
        textView.setLayoutParams(olp);
        return textView;
    }

    @Override
    public void getOrderAfterSaleStateError(Throwable throwable) {
        showShortText("请求失败");
    }

    @Override
    public void getOrderCancelRefundSuccess(OrderRefundCancelBean bean) {
        int code = bean.getCode();
        switch (code) {
            case 200:
                showShortText("取消成功");
                LogUtils.i("取消售后成功=======", "==================");
                //需要返回刷新
                //返回结果码给订单列表和订单详情页
                setResult(AppConstant.RESULT_CODE_CANCEL_REFUND);

                //取消售后成功发送消息通知消息列表页更新
                RxBus.getInstanceBus().post(
                        new OrderListEvent<>(
                                EventConstant.EVENT_TYPE_UPDATE_ORDER_LIST,
                                "取消售后成功")
                );

                finish();
                break;
            case 401:
                showShortText("参数有误");
                break;
            case 202:
                showShortText("请求失败");
                break;
            default:
                break;
        }
    }

    @Override
    public void getOrderCancelRefundError(Throwable throwable) {
        showShortText("取消售后失败");
    }

    @Override
    public void showProgress() {

    }

    @Override
    public void hideProgress() {

    }

    @Override
    public void onRequestSuccess(OrderRefundStateDataBean bean) {

    }

    @Override
    public void onRequestFailed(Throwable throwable) {

    }
}
